import axios from 'axios'
import qs from 'qs'
import { Message } from "element-ui";

import router from '@/router'



const Axios = axios.create({
    baseURL: "http://172.16.15.232:10000/sys",
    timeout: 5000,
    responseType: "json",
    withCredentials: false, // 是否允许带cookie这些
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
});
Axios.interceptors.request.use(
    config => {
        if (
            config.method === 'post' ||
            config.method === 'put' ||
            config.method === 'delete'
        ) {
            config.data = qs.stringify(config.data);
        }
        if (localStorage.token) {
            config.headers.Authorization = localStorage.token;
        }else{
            console.log('发起请求-没有token')
        }
        return config;
    },
    error => {
        Message({
            showClose: true,
            message: '请求错误',
            type: 'error'
        });
        return Promise.reject(error);
    }
)

Axios.interceptors.response.use(
    response => {

        let code = response.data.code;
        //请求正常
        if(code==0){
            return response.data;
        }
        //token无效
        else if(code==1){
            console.log("token无效")
            router.replace('/login')
        }
        //用户其他地方登录
        else if(code==7){
            console.log("用户在其他地方登录")
            router.replace('/login')
            Message({
                showClose: true,
                message: '该账号在别处登录',
                type: 'error'
            });
        }
        //没有权限
        else if(code==6){
            Message({
                showClose: true,
                message: '您没有该操作的权限',
                type: 'error'
            });
            // return Promise.reject(response.data);
        }
        //其他错误
        else{
            console.log(response.data)
            // return Promise.reject(response.data);
        }
        return Promise.reject(response.data);
    },
    error => {
        Message({
            showClose: true,
            message: '返回错误',
            type: 'error'
        })
        console.log("error",error)
        return Promise.reject(error);
    }
);

function fetch(url, params) {
    return new Promise((resolve, reject) => {
        Axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch(error => {
                reject(error)
            })
    });
}

export default {
    fetch
}